<template>
  <div class="content">
    <el-card style="margin-bottom: 20px">
      <div style="display: flex; align-items: center; justify-content: space-between">
        <el-button type="primary" @click="addUserInfo">添加</el-button>
        <div>
          用户名：
          <el-input v-model="params.username" style="width: 240px; margin-right: 20px" placeholder="请输入用户名" />
          手机号：
          <el-input v-model="params.phone" style="width: 240px; margin-right: 20px" placeholder="请输入手机号" />
          <el-button @click="getNewUserInfo" type="primary">搜索</el-button>
          <el-button @click="clickReset">重置</el-button>
        </div>
      </div>
    </el-card>
    <el-card>
      <!-- 底部table列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column show-overflow-tooltip prop="userId" label="用户ID" />
        <el-table-column show-overflow-tooltip prop="nickName" label="昵称" />
        <el-table-column show-overflow-tooltip prop="username" label="账号" />
        <el-table-column show-overflow-tooltip prop="email" label="邮箱" />
        <el-table-column show-overflow-tooltip prop="phone" label="手机号" />
        <el-table-column show-overflow-tooltip prop="roleName" label="角色名称" />
        <el-table-column show-overflow-tooltip prop="roleId" label="绑定角色ID" />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button size="small" @click="clickViewUserInfo(scope.row)" :icon="View">查看</el-button>
            <el-button size="small" @click="clickEditUserInfo(scope.row)" :icon="EditPen" type="primary">编辑</el-button>
            <el-popconfirm
              class="box-item"
              title="删除后将无法回复，是否删除"
              placement="top-end"
              @confirm="delUserInfo(scope.row)"
            >
              <template #reference><el-button size="small" :icon="Delete" type="danger">删除</el-button> </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page-content" v-if="total / params.pageSize > 1">
        <el-pagination
          background
          :total="total"
          layout="prev, pager, next"
          :page-size="params.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 添加 / 编辑 -->
    <el-dialog v-model="userDrawerShow" :title="userType == 0 ? '添加项目' : userType == 1 ? '查看项目' : '编辑项目'" width="500">
      <el-form :model="userInfo" label-width="auto" :rules="rules" ref="userForm">
        <el-form-item label="项目名称：" prop="projectName">
          <el-input placeholder="请输入项目名称" v-model="userInfo.projectName" :disabled="userType == 1" />
        </el-form-item>
        <el-form-item label="合作形式：" prop="cooperation">
          <el-select v-model="userInfo.cooperation" placeholder="请选择合作形式" :disabled="userType == 1">
            <el-option label="代播形式" value="0" />
            <el-option label="陪跑方式" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同金额：" prop="contractMoney">
          <el-input placeholder="请输入合同金额" v-model="userInfo.contractMoney" :disabled="userType == 1" />
        </el-form-item>
        <el-form-item label="合同是否完成：" prop="contractIsSuccess">
          <el-select v-model="userInfo.contractIsSuccess" placeholder="请选择是否完成" :disabled="userType == 1">
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否回款：" prop="isReturnedMoney">
          <el-select v-model="userInfo.isReturnedMoney" placeholder="请选择是否回款" :disabled="userType == 1">
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="起始日期：" prop="timeList">
          <el-date-picker
            v-model="userInfo.timeList"
            type="daterange"
            unlink-panels
            range-separator="-"
            @change="handleChangeTime"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="地区：" prop="addressList">
          <el-cascader v-model="userInfo.addressList" style="width: 100%" :options="addressList" @change="handleChange" />
        </el-form-item>

        <el-form-item v-if="userType !== 1">
          <el-button @click="clickAddForm" style="flex: 1" type="primary">保存</el-button>
          <el-button @click="clickFormReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="js" name="userInfo">
import { ref } from "vue";
import { Delete, EditPen, View } from "@element-plus/icons-vue";
import {
  getNewSysProjectTreeList,
  getNewAddProject,
  getNewEditUserTreeList,
  getNewDelUserTreeList,
  getNewSysRoleTreeList,
  getNewDistrictList
} from "@/api/modules/user";

const total = ref(0); // 总条数
const userType = ref(0);
const userForm = ref(null);
const tableData = ref([]); // 表格数据
const userDrawerShow = ref(false); // 抽屉显示隐藏

const userInfo = ref({
  projectName: "",
  cooperation: "",
  contractMoney: "",
  timeList: "",
  addressList: "",
  startTime: "",
  endTime: "",
  provinceId: "",
  cityId: "",
  districtId: ""
});
const rules = ref({
  projectName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  cooperation: [{ required: true, message: "请选择合作形式", trigger: "blur" }],
  contractMoney: [{ required: true, message: "请输入合同金额", trigger: "blur" }],
  timeList: [{ required: true, message: "请选择日期", trigger: "blur" }],
  addressList: [{ required: true, message: "请选择地区", trigger: "blur" }],
  contractIsSuccess: [{ required: true, message: "请选择合同是否完成", trigger: "blur" }],
  isReturnedMoney: [{ required: true, message: "请选择是否回款", trigger: "blur" }]
});

// 查看
const clickViewUserInfo = row => {
  userInfo.value = row;
  userType.value = 1;
  userDrawerShow.value = true;
};

// 角色身份
const sysRoleList = ref([]);
const addressList = ref([]);
const getSysRoleList = async () => {
  const res = await getNewSysRoleTreeList();
  if (res.code == 200) {
    sysRoleList.value = res.data;
  }

  const transformAddress = nodes => {
    return nodes.map(node => ({
      value: node.id, // 将id映射为value
      label: node.name, // 将name映射为label
      children: node.childrenNodeList ? transformAddress(node.childrenNodeList) : [] // 递归转换子节点
    }));
  };

  const addressRes = await getNewDistrictList();
  addressList.value = transformAddress(addressRes.data[0].childrenNodeList);
  console.log(addressList.value);
};
getSysRoleList();

// 编辑
const clickEditUserInfo = row => {
  userInfo.value = row;
  userType.value = 2;
  userDrawerShow.value = true;
};

// 删除
const delUserInfo = async row => {
  const res = await getNewDelUserTreeList({ userId: row.userId });
  if (res.code == 200) {
    getNewUserInfo();
  }
};

const params = ref({
  pageSize: 10,
  pageNo: 1,
  username: "",
  phone: ""
});

// 添加页码变化处理函数
const handleCurrentChange = currentPage => {
  // 更新当前页码参数
  params.value.pageNo = currentPage;
  // 重新加载数据
  getNewUserInfo();
};

// 重置
const clickReset = () => {
  params.value.phone = "";
  params.value.username = "";
};

// 重置表单
const clickFormReset = () => {
  userInfo.value = {
    projectName: "",
    cooperation: "",
    contractMoney: "",
    timeList: "",
    addressList: "",
    startTime: "",
    endTime: "",
    provinceId: "",
    cityId: "",
    districtId: ""
  };
};

// 省市区
const handleChange = value => {
  userInfo.value.provinceId = value[0];
  userInfo.value.cityId = value[1];
  userInfo.value.districtId = value[2];
};

// 时间
const handleChangeTime = value => {
  // 新增日期格式化函数
  const formatDate = date => {
    if (!date) return "";
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份补零
    const day = String(date.getDate()).padStart(2, "0"); // 日期补零
    return `${year}-${month}-${day}`;
  };
  userInfo.value.startTime = formatDate(value[0]);
  userInfo.value.endTime = formatDate(value[1]);
};

// 添加表单
const clickAddForm = async () => {
  const isValid = await new Promise(resolve => {
    userForm.value?.validate(valid => {
      resolve(valid);
    });
  });

  if (!isValid) return;

  if (userType.value == 0) {
    const res = await getNewAddProject(userInfo.value);
    if (res.code == 200) {
      userDrawerShow.value = false;
      getNewUserInfo();
    }
    return;
  }
  const resEdit = await getNewEditUserTreeList(userInfo.value);
  if (resEdit.code == 200) {
    userDrawerShow.value = false;
    getNewUserInfo();
  }
};

// 获取用户列表
const getNewUserInfo = async () => {
  const res = await getNewSysProjectTreeList(params.value);
  total.value = res.data.total;
  tableData.value = res.data.records;
};
getNewUserInfo();

// 添加用户
const addUserInfo = () => {
  userType.value = 0;
  userDrawerShow.value = true;
  userInfo.value.userId = "";
};
</script>
<style lang="scss" scoped>
.page-content {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
